package itsm.isperp.module.controller.knowledge;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.HtmlUtil;
import itsm.isperp.framework.web.paging.RenderPager;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.dto.solr.SolrKngKnowledgeDTO;
import itsm.isperp.module.entity.knowledge.KngMyfavorite;
import itsm.isperp.module.service.knowledge.KngKnowledgeCommentService;
import itsm.isperp.module.service.knowledge.KngKnowledgeItemService;
import itsm.isperp.module.service.knowledge.KngMyfavoriteService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 数据导入控制器
 * 
 * @author lizx
 * @date 2013-5-4
 */
@Controller
@RequestMapping("knowledge/knowledgeSearch")
public class KngKnowledgeSearchController {

	@Autowired
	protected KngKnowledgeItemService kngKnowledgeItemService;

	@Autowired
	protected KngMyfavoriteService kngMyfavoriteService;

	@Autowired
	protected KngKnowledgeCommentService kngKnowledgeCommentService;

	/**
	 * 搜索页面
	 * 
	 * @return
	 */
	@RequestMapping(value = { "manage", "" })
	public ModelAndView manage() {
		ModelAndView mv = new ModelAndView("knowledge/knowledgeSearch/manage");

		mv.addObject("warmTop10Entities",
				kngKnowledgeItemService.getTop10Item());
		mv.addObject("newTop10Entities",
				kngKnowledgeItemService.getNewTop10Item(10,""));
		mv.addObject("myFavoriteEntities", kngMyfavoriteService
				.getMyfavoriteItem(ContextHolder.getLoginUsername()));
		return mv;
	}

	@RequestMapping("searchByKeyword")
	@ResponseBody
	public Page<SolrKngKnowledgeDTO> searchByKeyword(JqGridRequest req,
			String keyword) {
		return kngKnowledgeItemService.searchByKeyword(keyword, req, null,null);
	}

	@RequestMapping("searchResultView")
	public ModelAndView searchResult(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"knowledge/knowledgeSearch/searchResultView");
		String keyword = req.getParameter("keyword");
		String pageIndex = req.getParameter("page");
		String categoryId = req.getParameter("categoryId");

		mv.addObject("categoryId", categoryId);
		mv.addObject("keyword", keyword);

		int currentPage = 1;
		if (StringUtils.isNotEmpty(pageIndex)) {
			currentPage = Integer.parseInt(pageIndex);
		}

		Pageable pg = null;

		ArrayList<Criteria> cs = new ArrayList<Criteria>();

		if (StringUtils.isNotEmpty(categoryId)) {
			Criteria c = new Criteria("categoryPath");
			c.contains(categoryId);
			cs.add(c);
		}

		// JdbcTemplate jdbcTemplate =
		// ContextHolder.getSpringBean("jdbcTemplate");
		//
		// Collection<? extends GrantedAuthority> auths = ContextHolder
		// .getLoginUser().getAuthorities();
		//
		// String roles = "";
		// List<String> cates = null;
		// if (auths != null && auths.size() > 0) {
		// Iterator<? extends GrantedAuthority> it = auths.iterator();
		// roles += "'" + it.next().getAuthority() + "'";
		//
		// while (it.hasNext()) {
		// roles += ",'" + it.next().getAuthority() + "'";
		// }
		//
		// cates = jdbcTemplate.queryForList(
		// "SELECT category_id FROM app_role_kng_category WHERE app_role_id IN("
		// + roles + ")", String.class);
		// if (cates.size() == 0) {
		// return mv;
		// }
		// }

		if (StringUtils.isEmpty(keyword)) {
			pg = new PageRequest(currentPage, 5);
			JqGridRequest request = new JqGridRequest(pg);

			if (StringUtils.isNotEmpty(categoryId)) {
				request.addFilterRule("treenode_path", JqGridFilterRuleOp.cn,
						categoryId);
			}

			// String data = "";
			//
			// for (String cate : cates) {
			//
			// data += ",'" + cate + "'";
			// }
			//
			// request.addFilterRule("kng_knowledge_category_id",
			// JqGridFilterRuleOp.in, data.substring(1));

			Page<SolrKngKnowledgeDTO> r = this.kngKnowledgeItemService
					.findAllPublishedDetailByRequest(request);

			for (SolrKngKnowledgeDTO d : r) {
				d.setContents(HtmlUtil.delHTMLTag(d.getContents()));
			}

			mv.addObject(
					"pager",
					RenderPager.renderHtml(req, currentPage, 5,
							(int) r.getTotalElements()));

			mv.addObject("result", r);
			return mv;
		}
		pg = new PageRequest(currentPage - 1, 5);

		// Criteria c = new Criteria("categoryId");
		// c.contains(cates);
		// cs.add(c);

		Page<SolrKngKnowledgeDTO> page = kngKnowledgeItemService
				.searchByKeyword(keyword, pg,
						cs.toArray(new Criteria[cs.size()]),null);

		mv.addObject("pager", RenderPager.renderHtml(req, currentPage,
				pg.getPageSize(), (int) page.getTotalElements()));
		mv.addObject("result", page);
		return mv;

	}

	/**
	 * 编辑界面
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 */
	@RequestMapping("knowledgeInfoView")
	public ModelAndView knowledgeInfoView(String id, HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"knowledge/knowledgeSearch/knowledgeInfoView");
		String knowledgeId = req.getParameter("id");

		Map<String, Object> model = kngKnowledgeItemService
				.findOneDetailById(knowledgeId);
		mv.addObject("model", model);

		List<Map<String, Object>> comments = kngKnowledgeCommentService
				.findAllDetailByKnowledgeId(knowledgeId);
		mv.addObject("comments", comments);
		mv.addObject("commentCount", comments == null ? 0 : comments.size());

		// 阅读数增加1
		// info.setReadTimes(info.getReadTimes() + 1);
		kngKnowledgeItemService.increaseReadTimes(knowledgeId);

		boolean isInMyfavitor = kngMyfavoriteService.isInMyfavitor(knowledgeId);
		mv.addObject("isInMyfavitor", isInMyfavitor);

		return mv;

	}

	/**
	 * 编辑界面
	 * 
	 * @param id
	 *            唯一标识
	 * @return 编辑视图
	 */
	@RequestMapping("knowledgeDtoView")
	public ModelAndView knowledgeDtoView(String id, String sourceId,
			HttpServletRequest req) {
		ModelAndView mv = new ModelAndView(
				"knowledge/knowledgeSearch/knowledgeDtoView");

		SolrKngKnowledgeDTO model = kngKnowledgeItemService.findOneDto(id);
		mv.addObject("model", model);

		// 阅读数增加1
		// info.setReadTimes(info.getReadTimes() + 1);
		kngKnowledgeItemService.increaseReadTimes(sourceId);

		return mv;

	}

	/**
	 * 收藏知识
	 * 
	 * @param id
	 *            知识ID
	 */
	@RequestMapping("collectMyfavitorKng")
	@ResponseBody
	public ResultMessage collectMyfavitorKng(String id) {

		JqGridRequest jReq = new JqGridRequest();
		jReq.addFilterRule("knowledgeItemid", JqGridFilterRuleOp.eq, id);
		jReq.addFilterRule("loginUserAccount", JqGridFilterRuleOp.eq,
				ContextHolder.getLoginUsername());
		List<KngMyfavorite> list = kngMyfavoriteService.findAll(jReq)
				.getContent();
		if (list != null && list.size() > 0) {
		} else {
			KngMyfavorite kngMyfavorite = new KngMyfavorite();
			kngMyfavorite.setCollectTime(DateTime.now().toDate());
			kngMyfavorite.setKnowledgeItemid(id);
			kngMyfavorite.setLoginUserAccount(ContextHolder.getLoginUsername());
			kngMyfavoriteService.saveOrUpdate(kngMyfavorite);
		}

		return ResultMessage.success();
	}

}
